package edu.ynu.MyProject.controller;

import edu.ynu.MyProject.common.controller.LogicController;
import edu.ynu.MyProject.dao.IUserDAO;
import edu.ynu.MyProject.entity.User;
import edu.ynu.MyProject.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@Api("用户")
@RestController
@RequestMapping("/user")
public class UserController extends LogicController<UserService, IUserDAO, User,Long> {

    public UserController(@Autowired UserService service) {
        super(service);
    }

    @ApiOperation("登录请求")
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username, @RequestParam String password) {
        try {
            User user = service.login(username, password);
            return ResponseEntity.ok(user); // 返回用户信息
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return ResponseEntity.status(401).body("登录失败: " + e.getMessage());
        }
    }

    @ApiOperation("创建用户")
    @PostMapping("/create")
    public ResponseEntity<User> createUser(
            @RequestParam String username,
            @RequestParam String password) {

        try {
            // 调用服务层创建用户
            User user = service.createUser(username, password);
            return ResponseEntity.ok(user);  // 返回200和创建的用户对象
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            // 处理错误，返回400状态和错误信息
            return ResponseEntity.badRequest().body(null);
        }
    }

    @ApiOperation("修改密码")
    @PutMapping("/update-password")
    public ResponseEntity<String> updatePassword(
            @RequestParam String username,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {

        try {
            // 调用服务层更新密码
            service.updatePassword(username, oldPassword, newPassword);
            return ResponseEntity.ok("密码更新成功");
        } catch (IllegalArgumentException e) {
            // 处理错误，返回400和错误信息
            return ResponseEntity.badRequest().body("旧密码不正确");
        }
    }

    @ApiOperation("根据用户名查询用户")
    @GetMapping("/get/{username}")
    public ResponseEntity<User> getUserByUsername(@PathVariable String username) {
        try {
            // 调用服务层获取用户信息
            User user = service.getUserByUsername(username);
            return ResponseEntity.ok(user);  // 返回200和用户对象
        } catch (IllegalArgumentException e) {
            // 用户未找到，返回404
            return ResponseEntity.notFound().build();
        }
    }
}